import hashFileAysc from "./HashFile";
import fetchData from "./ApiFetch";
import sliceFileAsyc from "./SliceFile";
import { postUpload, updateUpload } from "../app/features/progressSlice";
const apiUrl = process.env.REACT_APP_API_URL;

var total = 0;
var curr = 0;

async function chunkUpload(chunkId, fileName, chunkIdx, chunkSize,chunk, parentId, onUpdate) {
    const checkChunk = await fetchData(`${apiUrl}/file/checkChunk`, 'POST', {chunkId , fileName, chunkIdx, chunkSize});
    if (checkChunk.data.uploaded === false) {
        const resp = await fetchData(`${apiUrl}/file/chunkUpload`, 'POST', {chunkId , fileName, chunkIdx, chunkSize, chunk, parentId});
        curr += 1;
    } else {
        curr += 1;
    }
    onUpdate(curr, curr/total);
}

async function finishChunkUpload(chunkId, fileName, parentId) {
    const resp = await fetchData(`${apiUrl}/file/finishChunkUpload`, 'POST', {chunkId , fileName, parentId});
}

var uploadFileCount = 0;

function doFileUpload(file, parentId, dispatch, onFinished) {
    if (file !== null) {
        const currCount = uploadFileCount;
        uploadFileCount += 1;
        dispatch(postUpload({id:currCount, fileName: file.name, state: 0}));
        hashFileAysc(file).then(({fileHash}) => {
            console.log(file);
            console.log(`fileHash = ${fileHash}`)
            async function initUpload() {
                let chunkSize = 4194304;
                let chunks = Math.ceil(file.size / chunkSize);
                total = chunks;
                curr = 0;
                console.log(total);
                const resp = await fetchData(`${apiUrl}/file/initChunkUpload`, 'POST', {fileName: file.name, fileHash:fileHash,numChunk:chunks, parentId: parentId});
                dispatch(updateUpload({id:currCount, fileName: file.name, state: 1}));
                function updateProgress(curr, progress) {
                    if (progress !== 1) {
                        dispatch(updateUpload({id:currCount, fileName: file.name, state: 1, progress:progress}));
                    } else {
                        dispatch(updateUpload({id:currCount, fileName: file.name, state: 2, progress:progress}));
                        onFinished();
                    }
                }
                
                sliceFileAsyc(file, (data)=>{
                    chunkUpload(resp.data.chunkId, file.name, data.currentChunk, data.chunkSize,new Blob([data.chunk]), parentId, updateProgress  )
                },
                (data) => {
                }
                );
            }
            initUpload();
            
        });
    }
}


export default doFileUpload;